<template>
  <!-- 选择人员 -->
  <el-dialog
    title="选择组织"
    min-width="670px"
    :before-close="handlePersonnelClose"
    :visible.sync="dialogPersonnelVisible"
    custom-class="el-dialog-flex"
    class="peopleDialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @open="openSelectPersonnel"
  >
    <el-container>
      <el-aside style="float: left;width: 360px;">
        <!-- 头部操作按钮 -->
        <el-card class="box-card el-card-flex">
          <div slot="header" class="clearfix">
            <el-input clearable v-model="searchValue"  placeholder="请输入组织">
            </el-input>
          </div>
          <div class="text item el-over-auto" v-show="treeShow">
            <el-tree
              :data="employeesTree"
              v-show="searchValue"
              default-expand-all
              :highlight-current="true"
              :ref="searchValue?'tree':''"
              node-key="orgId"
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
            </el-tree>
            <el-tree
              v-show="!searchValue"
              :highlight-current="true"
              :default-expanded-keys="treeExpandedKey"
              :ref="!searchValue?'tree':''"
              node-key="orgId"
              :props="defaultProps"
              :load="loadMailNode"
              @node-click="handleNodeClick"
              :key="keyTree"
              lazy
            >
            </el-tree>
          </div>
          <div class="text item el-over-auto" v-show="peopleShow">
            <el-tree
              :data="employeesTree"
              v-show="searchValue"
              default-expand-all
              :highlight-current="true"
              :ref="searchValue?'tree':''"
              node-key="orgId"
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
            </el-tree>
            <!-- <ul class="text mid-panels">
              <li class="el-box panel" v-for="(val, index) in employeesPeople" :key="index" @click="choosePelple(val)">
                <div class="user-avatar">{{val.empName}}</div>
                <div class="listRightPart">
                  <span class="name">{{val.empName}}/{{val.empCode}}</span>
                  <span class="dept">{{val.positionStr}}</span>
                </div>
              </li>
            </ul> -->
          </div>
        </el-card>
      </el-aside>
      <el-main class="rightSection">
        <div class="box-card el-card-flex">
          <div class="count">
            <span>已选择 ({{employeesData.length}})</span>
            <el-button type="text" style="float: right;" @click="removeAll">清除</el-button>
          </div>
          <ul class="mid-panel">
            <li class="el-box" v-for="(val, index) in employeesData" :key="index">
              <!-- <div class="user-avatar">{{val.orgName}}</div> -->
              <div class="listRightPart">
                <span>{{val.orgName}}</span>
                <span class="dept">{{val.orgTypeName}}</span>
              </div>
              <i class="el-icon-minus" @click="removeClick(index)"></i>
            </li>
          </ul>
        </div>
      </el-main>
    </el-container>
    <span slot="footer" class="dialog-footer" style="text-align:right;width:100%;display:inline-block;margin-top:20px;">
      <el-button type="primary" @click="handleClick(true)">确定 <i class="el-icon-document-checked el-icon--right"></i></el-button>
      <el-button @click="handleClick(false)">取消 <i class="el-icon-refresh-left"></i></el-button>
    </span>
  </el-dialog>
</template>
<script>
import { Tree, Dialog, Table, TableColumn, Pagination, MessageBox, Message, Tabs, TabPane, Calendar, Upload, Drawer, Divider } from 'element-ui'
import { orgRoot, orgParent, orgSearch } from '@/api/library/enterpriseLibrary.js'
export default {
  props: ['dialogPersonnelVisible', 'schedulePersonList', 'multiple'],
  components: {
    'el-tree': Tree, // 树形菜单
    'el-dialog': Dialog, // 对话框
    'el-table': Table, // 表格
    'el-table-column': TableColumn, // 表格列
    'el-pagination': Pagination, // 分页
    'el-tabs': Tabs, // 标签
    'el-tab-pane': TabPane, // 标签页
    'el-calendar': Calendar, // 日历
    'el-upload': Upload, // 上传附件
    'el-drawer': Drawer, // 抽屉弹框
    'el-divider': Divider
  },
  data() {
    return {
      searchValue: '', // 树结构上的搜索
      defaultProps: {
        label: 'orgName',
        isLeaf: 'isLeaf'
      },
      keyTree: 1,
      employeesTree: [], // 树形结构搜索得到数据
      orgId: "", // 树结构数据id
      treeExpandedKey: [],
      employeesData: [], // 选中人员
      man: 'el-icon-male',
      woman: 'el-icon-female',
      treeShow: true, // 隐藏树数据
      peopleShow: false, // 隐藏人员数据
      employeesPeople: [], // 得到人的列表
      treeStatus: '' // 判断树是否已经初始化
    }
  },
  // created() {
    // //console.log(this.schedulePersonList)
    // let json = JSON.parse(JSON.stringify(this.schedulePersonList))
    // let stringify = JSON.stringify(this.schedulePersonList)
    // let schedulePersonList = typeof stringify == 'string'?stringify:json
    // this.employeesData = schedulePersonList
  // },
  watch: {
    searchValue (val) { // 树搜索
      if (val) {
        this.employees = false
        this.employeesInfo = false
        this.treeShow = false
        this.peopleShow = true
        orgSearch(val).then(res => {
          if(res.data.code == 10000){
            let orgDatas = res.data.data
            this.deepChild(orgDatas)
            this.employeesTree = orgDatas
            //console.log(this.employeesTree)
          }
          
        })
      } else {
        this.searchValue = ""
        this.treeShow = true
        this.peopleShow = false
        this.keyTree += 1
      }
    }
  },
  methods: {
    openSelectPersonnel () {
		
      if (this.treeStatus !== '') {
        this.keyTree += 1
      }
      //console.log(this.schedulePersonList)
      if (this.schedulePersonList == undefined) return
      // let employeesData = JSON.parse(JSON.stringify(this.schedulePersonList))
      //console.log(this.schedulePersonList.orgName)
      if(this.schedulePersonList.orgName || this.schedulePersonList.orgName == ''){
        if(this.schedulePersonList.orgName == ''){
          this.employeesData = []
          return false
        }
        let employeesData = this.schedulePersonList.orgName.split(',')
        if(this.schedulePersonList.adminOrgId){
          //console.log('11')
          var employeesId = this.schedulePersonList.adminOrgId.split(',')
        }else{
          //console.log('22')
          //console.log([this.schedulePersonList.orgId])
          employeesId = [this.schedulePersonList.orgId]
        }
        

        //console.log(employeesData,177)
        // //console.log(employeesId,185)
        var employeesDataArr = []
        // employeesData.forEach((v)=>{
        //   //console.log(v,180)
        //   employeesDataArr.push({
        //     orgName: v,
        //     orgTypeName: '',
        //     orgId:
        //   })
        //   //console.log(employeesDataArr,185)
        // })
        for(var i=0;i<employeesData.length;i++){
            employeesDataArr.push({
            orgName: employeesData[i],
            orgTypeName: '',
            orgId:employeesId[i]
          })
        }
        //console.log(employeesDataArr,198)
        this.employeesData = employeesDataArr
      }else{
        //console.log(this.schedulePersonList,'vvv')
        this.schedulePersonList.forEach((v)=>{
			if(!v.orgName && v.valName){
				 v.orgName = v.valName
			}
			if(!v.orgId && v.propertyVal){
				v.orgId = v.propertyVal
			}
        })
        this.employeesData = JSON.parse((JSON.stringify(this.schedulePersonList)))
      }
      
     
    },
    // 获取数据
    loadMailNode (node, resolve) {
      this.treeStatus = "inited";
      if (node.level === 0) {
        orgRoot().then(res => {
          let partentData = res.data.data
          partentData.forEach(e => {
            if (e.isLeaf == 'n') {
              e.isLeaf = false
            } else {
              e.isLeaf = true
            }
          })
          resolve(partentData)
          this.orgId = partentData[0].orgId
          this.$refs.tree.setCurrentKey(this.orgId)
          this.treeExpandedKey = [this.orgId]
        }).catch(res => {
          resolve([])
        })
      } else {
        let id = node.data.orgId
        this.orgId = id
        orgParent(id).then(res => {
          let childDatas = res.data.data.records
          childDatas.forEach(e => {
            if (e.isLeaf == 'n') {
              e.isLeaf = false
            } else {
              e.isLeaf = true
            }
          });
          resolve(childDatas)
        }).catch(res => {
          resolve([])
        })
      } 
    },
     // 递归遍历树形数据源
    deepChild (val) {
      let $this = this
      if (val && Array.isArray(val) && val.length) {
        val.forEach(item => {
          if (typeof item === 'object') {
            item.orgId = item.id
            item.orgName = item.name
            $this.deepChild(item.children)
          }
        })
      }
    },
    filterNode (value, data) { // 树状图
      if (!value) return true
      return data.orgName.indexOf(value) !== -1
    },
    // 点击树事件
    handleNodeClick (node) {
    //   if (!node.isLeaf) { // 点击单个
        let nowDatas = node
        if (this.multiple) { // 是多选
          // let orgIds = this.employeesData.find((v) => v.orgId == nowDatas.orgId)
		  for(let i=0,len=this.employeesData.length;i<len;i++){
			  if(this.employeesData[i].orgId == nowDatas.orgId){
					return false
			  }
		  }
          this.employeesData.push(nowDatas)
        } else this.employeesData = [ nowDatas ] // 单选
    //   }
      //console.log(this.employeesData)
    },
    // 搜索人员点击事件
    choosePelple (data) {
      //console.log(data)
      let nowDatas = data
      if (this.multiple) { // 是多选
        let empCodes = this.employeesData.find((v) => v.empCode == nowDatas.empCode)
        if (empCodes) {
          //console.log('该数据已存在')
          return
        } else {
          this.employeesData.push(nowDatas)
        }
      } else this.employeesData = [ nowDatas ] // 单选
    },
    // 关闭选择人员按钮触发事件
    handlePersonnelClose () {
      this.employeesData = []
      this.$emit('dialogEmployeesData', false)
      // this.removeAll()
    },
    // 点击选择人员弹框确定/取消事件
    handleClick (result) {
		
      if (!result) {
        return this.handlePersonnelClose()
      }
      this.$emit('dialogEmployeesData', JSON.parse((JSON.stringify(this.employeesData))))
      
    },
    // 清除所有选中员工
    removeAll () {
      this.employeesData = []
    },
    // 移除单个选中人员事件
    removeClick (index) {
      this.employeesData.splice(index, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
  .rightSection {
    padding: 0 0 10px 10px;
    .count {
      // width: 100%;
      background: #fafafa;
      padding: 0 15px;
      height: 32px;
      line-height: 32px;
    }
    .mid-panel {
      margin-top:10px;
      height: 100%;
      overflow: auto;
      li {
        padding: 10px 12px 10px 20px;
        // width: 100%;
        font-size: 12px;
        color: #333333;
        position: relative;
        .user-avatar {
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          border-radius: 50%;
          color: #ffffff;
          background-color: #81C684;
        }
        .listRightPart {
          display: inline-block;
          padding-left: 10px;
          vertical-align: middle;
          .name{
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 14px;
            color: #333333;
            .el-icon-male {
              color: #409EFF;
            }
            .el-icon-female {
              color: pink
            }
          }
          .dept{
            display: block;
            font-size: 12px;
            color: #9e9e9e;
          }
        }
        .el-icon-minus{
          position: absolute;
          right: 10px;
          top: 28%!important;
          color: #9e9e9e;
          // display: none;
        }
        &:hover{
          cursor: pointer;
          background-color: #f7f7f7;
          .el-icon-minus {
            display: block;
          }
        }
      }
    }
  }
.mid-panels {
  li {
    padding: 15px 10px 7px;
    font-size: 12px;
    color: #333333;
    // overflow: hidden;
    .user-avatar {
      width: 40px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      border-radius: 50%;
      color: #ffffff;
      background-color: #81C684;
    }
    .listRightPart {
      display: inline-block;
      padding-left: 10px;
      vertical-align: middle;
      .name{
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 12px;
        color: #333333;
      }
      .dept{
        font-size: 12px;
        color: #9e9e9e;
      }
    }
    &:hover{
      cursor: pointer;
      background-color: #f7f7f7;
    }
  }
  .activePsn {
    background-color: #f7f7f7;
  }
  .loading {
    height: 20px;
    line-height: 20px;
    padding: 0 0 15px 100px;
  }
}
</style>
<style lang="scss">
.peopleDialog {
  .el-dialog__body {
    padding: 10px;
  }
}
</style>